<template>
  <div class="dashboard-editor-container">
    <PanelGroup :topList="topList" />
    <!-- <el-tooltip content="开启自动刷新" placement="top" value="true">
    <i class="el-icon-switch-button" style="
        z-index: 9999;
        position: fixed;
        right: 20px;
        color: red;
        border: none;
        border-radius: 50%;
        padding: 15px;
        font-size: 30px;
        cursor: pointer;
        box-shadow: 0px 4px 8px rgba(0, 0, 0, 0.1);
        transition: background-color 0.3s ease;
      "></i>
      </el-tooltip> -->
    <el-row :gutter="10">
      <el-col :xs="24" :sm="24" :lg="6">
        <div class="chart-wrapper">
          <!-- 域名解析排行top10 -->
          <eventTop :chartData="domainNameList" :title="`近${days}日网站访问排名top10`" />
        </div>
        <div class="chart-wrapper" style="margin-bottom: 0;">
          <!-- 终端状态分析 -->
          <accelerateUsers :prevenData='prevenData' title="终端状态分析" />
        </div>
      </el-col>
      <el-col :xs="24" :sm="24" :lg="12">
        <div class="chart-wrapper">
          <!-- 近7日事件趋势图 -->
          <LineChart :prevenData='prevenData' />
        </div>
        <div class="chart-wrapper" style="margin-bottom: 0;">
          <!-- 最近事件分析 -->
          <TransactionTable :prevenData='prevenData' />
        </div>
      </el-col>
      <el-col :xs="24" :sm="24" :lg="6">
        <div class="chart-wrapper">
          <!-- 近7日活跃软件分布图 -->
          <!-- <accelerateDomainName :prevenData='prevenData' :title="`近${prevenData.processDays}日活跃软件分布图`" /> -->
          <eventTop :chartData="softwareList" :title="`近${days}日活跃软件top10`" />

        </div>
        <div class="chart-wrapper" style="margin-bottom: 0;">
          <!-- 系统状态概览 -->
          <systemStatus :list="list" :Days="Days" />
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import Cookies from 'js-cookie'
import eventTop from './components/eventTop.vue'
import transversechart from './components/transversechart'
import PanelGroup from './components/PanelGroup'
import LineChart from './components/LineChart'
import systemStatus from './components/systemStatus'
import recentlyAccelerated from './components/recentlyAccelerated'
import accelerateDomainName from './components/accelerateDomainName'
import accelerateUsers from './components/accelerateUsers'
import TransactionTable from './components/TransactionTable'
import { formatDuration, parseTime } from '@/utils/index.js'
import { connrequest, connrequest2 } from '@/api/firstPage.js'

export default {
  name: 'DashboardAdmin',
  inject: ["reload"],
  components: {
    PanelGroup,
    LineChart,
    systemStatus,
    recentlyAccelerated,
    accelerateDomainName,
    accelerateUsers,
    TransactionTable,
    transversechart,
    eventTop
  },
  data() {
    return {
      domainNameList: [],
      softwareList: [],
      deviceStatusList: [],
      list: {},
      days: 7,
      topList: {
        workingStatus: {

        }
      },
      prevenData: {
        EventLogDays: 7,
        EventLogTotal: 10,
        processDays: 7
      },
      day: 1,
      Days: 0,
      control: true
    }
  },
  mounted() {
    this.getData()

  },
  beforeDestroy() {
    // 在组件销毁前清理定时器
    clearInterval(this.refreshIntervalId);
    this.refreshIntervalId = null;
    this.control = false
  },
  methods: {
    async getData() {
      const res1 = await connrequest2('GetFirstPageParam')
      await this.GetThresholdConfig() //新增，用来获取首页数据展示天数
      this.prevenData = res1.Data || {}
      this.prevenData.EventLogDays = this.days || 7
      this.prevenData.EventLogTotal = this.prevenData?.EventLogTotal || 10
      this.prevenData.processDays = this.days || 7
      // 看不懂这里的业务，GetFirstPageParam接口什么都没返回
      
      this.getTopList()
      this.GetWindowProcSumGroupByProcName()
      this.GetURLVisitSumGroupByDomainCount()
      this.getCenterGetFirstPage()
      this.getPageInfo()
    },
    // 获取配置
    async GetThresholdConfig() {
      const res = await connrequest('GetThresholdConfig');
      const target = res.Data.find(item => item.Name === 'home_page_data_days');
      if (target) {
        this.days = target.Value;
      }
    },
    // 获取顶部状态
    async getTopList() {
      const data3 = {
        Paging: {
          QueryPageNo: 1,
          QueryPageLength: 1000000
        },
        Filter: {
          DeviceClass: "Windows",
        }
      }
      let endTime = new Date(new Date().setHours(0, 0, 0, 0)).getTime()
      let startTime = endTime - ((this.days || 7) * 1 * 3600 * 24 * 1000);
      const data4 = {
        Filter: {
          StartTime: parseTime(startTime),
          EndTime: '',
        }
      }
      const resT1 = await connrequest2('GetDeviceOnOffExceptSum')
      const resT2 = await connrequest2('GetDeviceStatusSum')
      const resT3 = await connrequest2('GetDeviceOldHardwareStatusSum', data3)
      const resT4 = await connrequest2('GetWindowProcPerfScore', data4)
      this.$set(this.topList, 'Online', resT1.Data?.Online)
      this.$set(this.topList, 'Offline', resT1.Data?.Offline)
      this.$set(this.topList, 'Exception', resT1.Data?.Exception)
      const result = resT2.Data.reduce((obj, item) => {
        obj[item.Name] = item.Count;
        return obj;
      }, {});
      this.$set(this.topList, 'workingStatus', result)
      this.$set(this.topList, 'LowerDeviceCount', resT3.Data?.LowerDeviceCount)
      this.$set(this.topList, 'OldDeviceCount', resT3.Data?.OldDeviceCount)
      this.$set(this.topList, 'Score', resT4.Data.Score)
    },
    // 网站访问排名
    async GetURLVisitSumGroupByDomainCount() {
      let endTime = new Date(new Date().setHours(0, 0, 0, 0)).getTime()
      let startTime = endTime - ((this.days || 7) * 1 * 3600 * 24 * 1000);
      const data = {
        Filter: {
          StartTime: parseTime(startTime),
          EndTime: '',
        }
      }
      const res = await connrequest2('GetURLVisitSumGroupByDomainCount', data)
      let domainNameList = []
      res.Data.map(item => {
        domainNameList.push({ Name: `${item.Domain || '未知'} ${item.Class ? `(${item.Class})` : ''}`, Count: item.Count })
        return item
      })
      this.domainNameList = domainNameList
    },
    // 活跃软件top10
    async GetWindowProcSumGroupByProcName() {
      let arr = []
      let endTime = new Date(new Date().setHours(0, 0, 0, 0)).getTime()
      let startTime = endTime - ((this.days || 7) * 1 * 3600 * 24 * 1000);
      const data = {
        Filter: {
          StartTime: parseTime(startTime),
          EndTime: parseTime(endTime),
        }
      }
      const res = await connrequest2('GetWindowProcSumGroupByProcName', data);
      res.Data = res.Data || []
      res.Data.map(item => {
        arr.push({ Name: item.Name || '其他', Count: item.Count || 0 })
      })
      this.softwareList = arr
    },
    // 获取系统状态
    async getCenterGetFirstPage() {
      const res = await connrequest2('CenterGetFirstPage')
      let d = Math.floor(res.Data.KeepRunningSeconds / 3600 / 24);
      let h = Math.floor((res.Data.KeepRunningSeconds % 86400) / 3600);
      var m = Math.floor(((res.Data.KeepRunningSeconds % 86400) % 3600) / 60);
      res.Data.KeepRunningSeconds = `${d < 1 ? '' : d}${d < 1 ? '' : '天'} ${h}小时 ${m}分钟`;
      res.Data.EthIP = res.Data.EthIP ? res.Data.EthIP : '接口无效'
      res.Data.WifiIP = res.Data.WifiIP ? res.Data.WifiIP : '接口无效'
      let now = new Date().getTime()
      this.Days = Math.floor((res.Data.ValidTime * 1000 - now) / 86400 / 1000)
      res.Data.ValidTime = parseTime(res.Data.ValidTime, '{y}-{m}-{d}')
      res.Data.CurrentTime = parseTime(res.Data.CurrentTime)
      res.Data.MemUsedPct = ((res.Data.MemUsed / res.Data.MemTotal) * 100).toFixed(1) * 1
      res.Data.MemUsed = (res.Data.MemUsed / 1000000).toFixed(2) + 'G'
      res.Data.MemTotal = (res.Data.MemTotal / 1000000).toFixed() + 'G'
      res.Data.DiskUsedPct = ((res.Data.DiskUsed / res.Data.DiskTotal) * 100).toFixed(1) * 1
      res.Data.DiskUsed = (res.Data.DiskUsed / 1000000).toFixed(2) + 'G'
      res.Data.DiskTotal = (res.Data.DiskTotal / 1000000).toFixed(0) + 'G'
      res.Data.AmazonUsedSeconds = formatDuration(res.Data.AmazonUsedSeconds)
      this.list = { ...res.Data }
    },
    async getPageInfo() {
      this.prevenData.AutomaticRefreshInterval = this.prevenData.AutomaticRefreshInterval || 0
      if (this.prevenData.AutomaticRefreshInterval && this.control) {
        this.refreshIntervalId = setInterval(() => {
          this.reload()
        }, this.prevenData.AutomaticRefreshInterval * 1000);
      }
    },
    // 获取域名分类
    async GetParamDictURL() {
      const res = await connrequest('GetParamDictURL')
      window.sessionStorage.setItem('ParamDictURL', JSON.stringify(res.Data))
    }
  }
}
</script>

<style lang="scss" scoped>
@import "~@/styles/variables.scss";

::v-deep .chart-wrapper {
  background: #fff;
  padding: 16px 16px 0;
  margin-bottom: 10px;
  height: calc(50vh - 67.5px) !important;
  overflow: hidden;

  @media (max-width: 1920px) {

    .el-table--medium th,
    .el-table--medium td {
      padding: 3px 0 !important;
    }
  }
}

::v-deep .el-table__body-wrapper::-webkit-scrollbar {
  width: 3px !important;
  background-color: #F5F5F5 !important;
}

::v-deep .el-table__body-wrapper::-webkit-scrollbar-track {
  box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3) !important;
  background-color: #F5F5F5 !important;
}

::v-deep .el-table__body-wrapper::-webkit-scrollbar-thumb {
  border-radius: 10px !important;
  box-shadow: inset 0 0 6px rgba(0, 0, 0, .3) !important;
  background-color: #999 !important;
}

@media (max-width:1024px) {
  .chart-wrapper {
    padding: 8px;
  }
}
</style>